<html>
<head>
  <title>Sample Login Page</title>
	<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
  <script src="https://sdk.amazonaws.com/js/aws-sdk-2.3.7.min.js"></script>
	<script>
  AWS.config.region = '<REGION>';
	AWS.config.credentials = new AWS.CognitoIdentityCredentials({
    IdentityPoolId: '<IDENTITY_POOL_ID>'
  });
  var lambda = new AWS.Lambda();
	</script>
  <h1>Sample Login Page</h1>
  <div id="info">
  Login
  </div>
  <table>
    <tr>
      <td>Email</td>
      <td><input type="email" id="email" size="20">
    </tr>
    <tr>
      <td>Password</td>
      <td><input type="password" id="password" size="20">
    </tr>
    <tr>
      <td colspan="2">
        <button type="submit" id="login-button">Login</button>
      </td>
    </tr>
		<tr>
      <td colspan="2" class="center">
				<a href="index.html">Back</a>
      </td>
    </tr>
  </table>
  <script>
  var info = document.getElementById('info');
  var email = document.getElementById('email');
  var password = document.getElementById('password');
  var loginButton = document.getElementById('login-button');
  loginButton.addEventListener('click', function() {
    info.innerHTML = 'Login...';
    if (email.value == null || email.value == '') {
      info.innerHTML = 'Please specify your email address.';
    } else if (password.value == null || password.value == '') {
      info.innerHTML = 'Please specify a password.';
    } else {
      var input = {
        email: email.value,
        password: password.value
      };
      lambda.invoke({
        FunctionName: 'LambdAuthLogin',
        Payload: JSON.stringify(input)
      }, function(err, data) {
        if (err) console.log(err, err.stack);
        else {
          var output = JSON.parse(data.Payload);
          if (!output.login) {
            info.innerHTML = '<b>Not</b> logged in';
          } else {
            info.innerHTML = 'Logged in with IdentityId: ' + output.identityId + '<br>';
            var creds = AWS.config.credentials;
	    creds.params.IdentityId = output.identityId;
	    creds.params.Logins = {
	      'cognito-identity.amazonaws.com': output.token
	    };
	    creds.expired = true;
	    // Do something with the authenticated role
          }
        }
      });
		}
  });
  </script>
</body>
</html>
